<?php

namespace app\admin\controller\project;

use app\common\controller\Backend;

class Project extends Backend
{
    /**
     * 当前控制器下的一个模型属性
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = ['subject.id', 'title', 'cate.name', 'price'];

    // 初始化
    public function __construct()
    {
        parent::__construct();
        // 引入的模型
        $this->ProjectModel = model('Project.Project');
        $this->OrderModel = model('Project.Order');
        $statusList=[
            '0' => '未开始',
            '1' => '开始报名',
            '2' => '截至报名',
            '3' => '开始活动',
            '4' => '结束活动',
        ];
        $OrderStatus=[
            '0' => '未开始',
            '1' => '已开始',
            '2' => '已结束',
        ];
        $this->assign([
            'statusList'=>$statusList,
            'OrderStatus'=>$OrderStatus,
        ]);
        
    }
    public function index()
    {
        if ($this->request->isAjax()) 
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->ProjectModel
                ->where($where)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->ProjectModel
                ->where($where)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->SubjectOrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    // 开始报名和截至报名
    public function signtoggle($ids=null)
    {
        if($this->request->isAjax())
        {
            $project=$this->ProjectModel->find($ids);
            if(!$project)
            {
                $this->error("预约活动不存在");
                exit;
            }
            $data=[
                'id'=>$ids,
            ];
            // 开始报名
            if($project['status']=='0')
            {
                $data['status']='1';
            }
            // 截至报名
            if($project['status']=='1')
            {
                $data['status']='2';
            }
            halt($data);
            $result=$this->ProjectModel->isUpdate(true)->save($data);
            if($project['status']=='0' && $result === FALSE)
            {
                $this->error('开始报名失败');
                exit;
            }
            if($project['status']=='1' && $result === FALSE)
            {
                $this->error('截至报名失败');
                exit;
            }
            $this->success();
            exit;
        }
    }

    // 开始活动和结束活动
    public function ActionToggle($ids=null)
    {
        if($this->request->isAjax())
        {
            $project=$this->ProjectModel->find($ids);
            if(!$project)
            {
                $this->error("预约活动不存在");
                exit;
            }
            // 查询预约订单
            $order=$this->OrderModel->where(['pid'=>$ids])->select();
            if($order)
            {
                foreach($order as $item)
                {
                    $OrderData=[
                        'id'=>$item['id'],
                    ];
                    if($project['status'] == '2')
                    {
                        $OrderData['status']='1';
                    }
                    if($project['status'] == '3')
                    {
                        $OrderData['status']='2';
                    }
                    // dump($OrderData);
                    // $OrderStatus=$this->OrderModel->isUpdate(true)->save($OrderData);
                }
            }
            // exit;
            $data=[
                'id'=>$ids,
            ];
            if($project['status'] == '2')
            {
                $data['status']='3';
            }
            if($project['status'] == '3')
            {
                $data['status']='4';
            }
            halt($data);
            $result=$this->ProjectModel->isUpdate(true)->save($data);
            if($project['status'] == '2' && $result === FALSE)
            {
                $this->error('开始活动失败');
                exit;
            }
            if($project['status'] == '3' && $result === FALSE)
            {
                $this->error('结束活动失败');
                exit;
            }
            $this->success();
            exit;
        }
    }

    // 查看订单
    public function order($ids=null)
    {
        if ($this->request->isAjax()) 
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wherenew=[
                'pid'=>$ids
            ];
            $total = $this->OrderModel
                ->with(['business'])
                ->where($where)
                ->where($wherenew)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->count(); //查询总数

            $list = $this->OrderModel
                ->with(['business'])
                ->where($where)
                ->where($wherenew)
                ->order($sort, 'asc')
                ->limit($offset, $limit)
                ->select(); //查询数据
            // echo   $this->OrderModel->getlastSql();exit;
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            // 转换时间格式
            $params['createtime']=strtotime($params['createtime']);
            $params['endtime']=strtotime($params['endtime']);
            // let data=new Date();
            // halt($params);
            $result=$this->ProjectModel->validate('commmo/Project/Project')->save($params);
            if($result === FALSE)
            {
                $this->error($this->ProjectModel->getError());
                exit;
            }
            $this->success();
            exit;
        }
        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->ProjectModel->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }
        // halt($row->toArray());
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // 转换时间格式
            $params['createtime']=strtotime($params['createtime']);
            $params['endtime']=strtotime($params['endtime']);
            $params['id'] = $ids;
            // halt($params);

            // 查询预约订单数据
            $order=$this->OrderModel->where(['pid'=>$ids])->select();

            // 活动表状态改变，预约订单表的状态随之改变
            if($order && $params['status'] <= '2'  )
            {
                foreach($order as $item)
                {
                    $OrderData=[
                        'id'=>$item['id'],
                        'status'=>'0'
                    ];
                    $OrderStatus=$this->OrderModel->isUpdate(true)->save($OrderData);
                    if($OrderStatus === FALSE)
                    {
                        $this->error('更新预约订单失败');
                        exit;
                    }
                }
            }

            if($params['status'] == '3' && $order)
            {
                foreach($order as $item)
                {
                    $OrderData=[
                        'id'=>$item['id'],
                        'status'=>'1'
                    ];
                    $OrderStatus=$this->OrderModel->isUpdate(true)->save($OrderData);
                    if($OrderStatus === FALSE)
                    {
                        $this->error('更新预约订单失败');
                        exit;
                    }
                }
            }
            if($params['status'] == '4' && $order)
            {
                foreach($order as $item)
                {
                    $OrderData=[
                        'id'=>$item['id'],
                        'status'=>'2'
                    ];
                    $OrderStatus=$this->OrderModel->isUpdate(true)->save($OrderData);
                    if($OrderStatus === FALSE)
                    {
                        $this->error('更新预约订单失败');
                        exit;
                    }
                }
            }
       
            $result = $this->ProjectModel->validate("common/Project/Project")->isUpdate(true)->save($params);
            if ($result === FALSE) {
                if ($params['thumbs'] && $params['thumbs'] != $row['thumbs']) {
                    $thumbs = substr($params['thumbs'], 1);
                    @is_file($thumbs) && @unlink($thumbs);
                }
                $this->error($this->ProjectModel->getError());
                exit;
            } else {
                if ($params['thumbs'] && $params['thumbs'] != $row['thumbs']) {
                    $thumbs = substr($row['thumbs'], 1);
                    @is_file($thumbs) && @unlink($thumbs);
                }
            }
            $this->success();
            exit;
        }
        $this->assign("row", $row);
        return $this->view->fetch();
    }

    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ? explode(',', $ids) : [];
        $row = $this->ProjectModel->column('id');

        $OrderList=[];
        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__("没有找到该活动"));
                exit;
            }
            $where=[
                'pid'=>$item,
            ];
            $order=$this->OrderModel->where(['pid'=>$item])->column('id');
            $OrderList=array_merge($order,$OrderList);
        }

        // 有预约订单
        if($OrderList)
        {
            $OrderStatus=$this->OrderModel->destroy($OrderList);
            if($OrderStatus === FALSE)
            {
                $this->error('删除预约订单失败');
                exit;
            }
        }
        
        $result = $this->ProjectModel->destroy($ids);
        if ($result === FALSE) {
            $this->error($this->ProjectModel->getError());
            exit;
        }
        $this->success();
        exit;
    }
}